package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@WebServlet("/ipcount")
public class CountIpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //resp.setContentType("text/html;charset=utf-8");
        InputStream resourceAsStream = getClass().getResourceAsStream("/IP.txt");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream,"utf-8"));
        String str = null;
        Map<String,Integer> map = new HashMap<String,Integer>();
        while((str=bufferedReader.readLine())!=null){
            if(!map.containsKey(str)){
                int val = 1;
                map.put(str,val);
            }else{
               map.put(str,map.get(str)+1);
            }
        }
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            resp.getWriter().println(entry.getKey()+"---"+entry.getValue());
        }
        bufferedReader.close();
        resourceAsStream.close();
    }
}
